<template>
  <div class="active_edit">
    <el-form
      ref="ruleFormRef"
      :model="arrForm"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
    >
      <el-form-item label="活动名称" prop="title" :rules="{ required: true, message: '请输入活动名称', trigger: 'blur' }">
        <el-input v-model="arrForm.title"></el-input>
      </el-form-item>
      <el-form-item label="活动时间" prop="rangeTime" :rules="{ required: true, message: '请选择活动开始时间', trigger: 'change' }">
        <el-date-picker
          v-model="arrForm.rangeTime"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="奖品设置">
        <div style="margin: 20px 0"  v-for="(item, index) of arrForm.prize" :key="index">
          <el-row :gutter="20">
            <el-col :span="11">
              <el-form-item
                class="rules"
                label-width="60px"
                label="奖项"
                :prop="`prize[${index}].name`" :rules="{ required: true, message: '请输入奖项名称', trigger: 'blur' }">
                <el-input  maxlength="12" type="text" :placeholder="一等奖" v-model="item.name" size="mini">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label-width="80px"
                label="名额"
                :prop="`prize[${index}].count`"
                :rules="{ required: true, message: '请输入数量', trigger: 'blur' }">
                <el-input
                  style="width: 120px"
                  size="mini"
                  :min="1"
                  :max="999"
                  v-model="item.count"
                  placeholder="请输入名额数量"
                />
              </el-form-item>
            </el-col>
            <el-button
              size="mini"
              type="text"
              style="border-radius: 2px; color: #b93947"
              @click="handleAdd(index)"
              v-if="arrForm.prize.length === index + 1">
              <i class="el-icon-circle-plus-outline"></i >&nbsp;添加</el-button>
            <el-button
              style="margin-top: 2px"
              v-if="arrForm.prize.length !== 1"
              type="text"
              class="deleteBox"
              @click="handleDel(index)">
              <i class="el-icon-delete"></i>&nbsp;删除</el-button>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="奖品" label-width="60px" :prop="`prize[${index}].award`" :rules="{ required: true, message: '请输入奖品', trigger: 'blur' }">
                <el-input v-model="item.award" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!--      { required: true, message: '请选择活动状态', trigger: 'change' }-->
      </el-form-item>
      <el-form-item label="活动描述" prop="description" :rules="{ required: true, message: '请输入活动描述', trigger: 'blur' }">
        <el-input v-model="arrForm.description" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="活动状态" prop="status" :rules="{ required: true, message: '请选择活动状态', trigger: 'change' }">
        <el-radio-group v-model="arrForm.status" >
          <el-radio-button label="正在进行"></el-radio-button>
          <el-radio-button label="已关闭"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleFormRef')"
        >Create</el-button
        >
        <el-button  @click="closeTag()">返回上一页</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted } from "vue";
import { editActivity, getActivity } from "../../api/activity";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import useCloseTag from "@/hooks/useCloseTag";
import { ElMessage } from "element-plus";

export default {
  name: 'ActivityEdit',
  setup() {
    const { closeTag } = useCloseTag()
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      ruleFormRef: ref(''),
      arrForm: {
        id: route.params.id,
        title: '',
        description: '',
        prize: [
          {
            name: '',
            award: '',
            count: '',
          },
        ],
        status: '',
        rangeTime: null,
      },
    })
    const methods = {
      async getActivityInfo() {
        let resp = await getActivity(state.arrForm.id)
        let info = resp.data.data
        state.arrForm = {
          id: info.id,
          title: info.title,
          description: info.description,
          prize: info.prize,
          status: info.status,
          rangeTime: ref([
            new Date(info.start_time),
            new Date(info.end_time),
          ])
        }
        console.log(state.arrForm.rangeTime)
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            state.arrForm.start_time = this.timeToUnix( state.arrForm.rangeTime[0])
            state.arrForm.end_time = this.timeToUnix( state.arrForm.rangeTime[1])
            delete state.arrForm.rangeTime
            let resp = await editActivity(state.arrForm)
            if (resp.code !== 200) {
              ElMessage({
                message: resp.message || '服务器错误！',
                type: 'error',
              })
            } else {
              ElMessage({
                message: resp.message || 'ok',
                type: 'success',
              })
              setTimeout(function() {
                store.dispatch('tags/delTag', route)
                router.back()
              },1000)
            }
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
        state.arrForm.prize = {
          name: '',
          award: '',
          count: 1,
        }
      },
      timeToUnix(data) {
        let tmp = Date.parse( data ).toString();
        tmp = tmp.substr(0,10);
        return tmp
      },
      handleAdd(index) {
        state.arrForm.prize.push({
          name: '',
          award: '',
          count: 1,
        })
      },
      handleDel(index) {
        this.arrForm.prize.splice(index, 1)
      },
      formatDate(ns) {
        var d = new Date(ns*1000);
        var month = (d.getMonth()+ 1).toString().length == 1 ? '0'+(d.getMonth()+1) : d.getMonth() + 1;
        var date = d.getDate().toString().length == 1 ? '0'+d.getDate() : d.getDate();
        var hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours();
        var minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes();
        var seconds = d.getSeconds().toString().length == 1 ? '0'+d.getSeconds() : d.getSeconds();
        var dformat = [ d.getFullYear(), month, date].join('/')
          + ' ' + [ hours, minutes, seconds ].join(':');
        return dformat
      },
    }
    onMounted(()=>{
      methods.getActivityInfo()
    })
    return { ...toRefs(state), ...methods, closeTag}
  }
}
</script>

<style scoped>

</style>